const path = require('path')
const baseConfig = require('./webpack.base')
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const HtmlwebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const HTMLDirs = ['index', 'detail', 'play']
// 通过 html-webpack-plugin 生成的 HTML 集合
let HTMLPlugins = []
// 入口文件集合
let Entries = {}

const src = path.resolve('src')

// 生成多页面的集合
HTMLDirs.forEach((page) => {
  const htmlPlugin = new HtmlwebpackPlugin({
    filename: `${page}.html`,
    template: `${src}/html/${page}.html`,
    chunks: ['base', page],
  })
  HTMLPlugins.push(htmlPlugin)
  Entries[page] = `${src}/${page}.js`
})

Entries['base'] = `${src}/main.js`
Entries['m'] = `${src}/system.js`
Entries['style'] = `${src}/static/css/style.scss`

const webpackConfig = {
  mode: 'production',
  ...baseConfig,
  entry: Entries,
  plugins: [
    // 清空打包目录
    ...HTMLPlugins,
    new CleanWebpackPlugin(),
    new CopyPlugin({
      patterns: [
        {
          from: `${src}/static/img/blank.png`,
          to: path.resolve(__dirname, '..', 'dist') + '/img/blank.png',
        },
        {
          from: `${src}/static/emot`,
          to: path.resolve(__dirname, '..', 'dist') + '/emot',
        },
        {
          from: `${src}/static/zanpiancms`,
          to: path.resolve(__dirname, '..', 'dist') + '/zanpiancms',
        },
      ],
    }),
    new OptimizeCSSAssetsPlugin({
      assetNameRegExp: /\.css\.*(?!.*map)/g, //注意不要写成 /\.css$/g
      cssProcessor: require('cssnano'),
      cssProcessorOptions: {
        discardComments: {
          removeAll: true,
        },
        // 避免 cssnano 重新计算 z-index
        safe: true,
        // cssnano 集成了autoprefixer的功能
        // 会使用到autoprefixer进行无关前缀的清理
        // 关闭autoprefixer功能
        // 使用postcss的autoprefixer功能
        autoprefixer: false,
      },
      canPrint: true,
    }),
    // new BundleAnalyzerPlugin(),
    ...baseConfig.plugins,
  ],
}

module.exports = webpackConfig
